import { ref, nextTick } from 'vue'
import { nodeinfo } from '@/stores/nodeinfo'
import { storeInfo } from '@/stores/storeinfo'
import { uuid } from '@/utils/uuid'
import { useUserStore } from '@/stores/userStore'
const username = useUserStore().user.name;
export const useFileAdd = () => {
    const nodeinfoStore = nodeinfo()
    const storeinfo = storeInfo()
    const inputRefs = ref([])

    // 获取默认文件名（带序号）
    const getDefaultFileName = (stageItem: any) => {
        let defaultName = '新建文件'
        let counter = 1

        while (isFileNameDuplicate(stageItem, `${defaultName}${counter > 1 ? ` ${counter}` : ''}`)) {
            counter++
        }

        return `${defaultName}${counter > 1 ? ` ${counter}` : ''}`
    }

    // 检查文件名是否重复
    const isFileNameDuplicate = (stageItem: any, fileName: string, excludeIndex?: number) => {
        if (!stageItem.nodes) return false

        return stageItem.nodes.some((node: any, index: number) => {
            // 排除自身检查
            if (excludeIndex !== undefined && index === excludeIndex) return false
            return node.title === fileName
        })
    }
    const newNode = ref({})
    // 处理添加文件
    const handleAddFile = (item: any, classToFile: any, userId: string) => {
        console.log("点击获取的信息：", item)
        
        newNode.value = {
            nodeId:uuid(),
            title: '', // 初始为空，用户必须输入
            isEditing: true,
            editTitle: '', // 初始为空
            stage: item.stage,
            classId: classToFile.id,
            userId: userId,
            showDuplicateError: false
        }

        if (!item.nodes) {
            item.nodes = []
        }

        item.nodes.push(newNode)

        // 自动展开当前子菜单
        const subMenuIndex = item.stage.toString()
        const activeIndexes = document.querySelectorAll('.el-sub-menu.is-opened')
        activeIndexes.forEach(el => {
            if (el.getAttribute('index') !== subMenuIndex) {
                el.classList.remove('is-opened')
            }
        })

        // 确保当前子菜单展开
        nextTick(() => {
            const currentSubMenu = document.querySelector(`.el-sub-menu[index="${subMenuIndex}"]`)
            if (currentSubMenu && !currentSubMenu.classList.contains('is-opened')) {
                currentSubMenu.classList.add('is-opened')
            }

            // 聚焦到新添加的输入框
            if (inputRefs.value && inputRefs.value.length > 0) {
                const lastInput = inputRefs.value[inputRefs.value.length - 1]
                lastInput.focus()
            }
        })
    }

    // 保存节点标题（回车或失焦时触发）
    const saveNodeTitle = async (item: any, nodeIndex: number, classToFile: any) => {
        const node = item.nodes[nodeIndex]
        const newTitle = node.editTitle.trim()
        
        if (!newTitle) {
            // 如果标题为空，则删除该节点
            item.nodes.splice(nodeIndex, 1)
            return
        }

        // 检查文件名是否重复（排除自身）
        if (isFileNameDuplicate(item, newTitle, nodeIndex)) {
            node.showDuplicateError = true
            // 保持编辑状态
            node.isEditing = true
            // 重新聚焦输入框
            nextTick(() => {
                if (inputRefs.value && inputRefs.value[nodeIndex]) {
                    inputRefs.value[nodeIndex].focus()
                    inputRefs.value[nodeIndex].select()
                }
            })
            return
        }

        node.showDuplicateError = false
        node.title = newTitle
        node.isEditing = false

        const newNodeInfo = ref({
            nodeId: newNode.value.nodeId,
            title: newTitle,
            teacherId: '1',
            classId: classToFile.id,
            stage: item.stage,
            createdAuthor: username
        })
        console.log("新增笔记信息：", newNodeInfo.value)
        // 调用接口存入数据库
        await nodeinfoStore.insertnewNode(newNodeInfo.value)
        // 存入pinia
        storeinfo.setNewNodeInfo(newNodeInfo.value)
    }

    return {
        inputRefs,
        getDefaultFileName,
        handleAddFile,
        saveNodeTitle
    }
}